<?php

namespace backend\module\content\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use backend\module\content\models\Article;
use yii\helpers\ArrayHelper;
use backend\components\behaviors\SearchBehavior;
/**
 * ArticleSearch represents the model behind the search form about `backend\module\content\models\Article`.
 */
class ArticleSearch extends Article {
    public function behaviors() {
        return ArrayHelper::merge(parent::behaviors(), [
            SearchBehavior::className(),
        ]);
    }
    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['id', 'catid', 'userid'], 'integer'],
            [['title', 'thumb', 'content', 'description', 'keywords', 'url'], 'safe'],
            ['date_range', 'safe']
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios() {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params, $ids) {
        $query = Article::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }
        $query->where(['userid' => $this->userid, 'catid' => $ids]);
        $query->andFilterWhere([
            'id' => $this->id,
        ]);
        
        $query->andFilterWhere(['like', 'title', $this->title])
                ->andFilterWhere(['like', 'thumb', $this->thumb])
                ->andFilterWhere(['like', 'content', $this->content])
                ->andFilterWhere(['like', 'description', $this->description])
                ->andFilterWhere(['like', 'keywords', $this->keywords])
                ->andFilterWhere(['like', 'url', $this->url]);

        if($dataRange = $this->dataRange()){
            $query->andFilterWhere(['>', 'created', $dataRange[0]])
                  ->andFilterWhere(['<', 'created', $dataRange[1]]);
        }
        return $dataProvider;
    }

}
